package com.smp.service.impl;

import com.smp.service.RocketmqFacade;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author SmallPlume
 * @title: RocketmqFacadeImpl
 * @projectName Smpcloud-release
 * @description: TODO
 * @date 2020/3/16 15:53
 */
@Slf4j
@Service
public class RocketmqFacadeImpl implements RocketmqFacade {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void sendMes(String msg) {
        Message message = new Message("topic_family", "testtag", msg.getBytes());
        try {
            // 同步发送
            SendResult send = rocketMQTemplate.getProducer().send(message);
            log.info("Product-同步发送-Product信息={}", send);

            // 异步发送
            rocketMQTemplate.getProducer().send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("Product-异步发送-输出信息={}", sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    throwable.printStackTrace();
                    //补偿机制，根据业务情况进行使用，看是否进行重试
                }
            });

            // 单项发送
            rocketMQTemplate.getProducer().sendOneway(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
